package com.edgegateway.common.utils.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @AUTHOR Doooxu
 * @DATE 2022/12/6
 * @DESCRIBE
 */
@Component
public class BaseAuthHttpUtils {

    public static String authUsername;

    public static String authPassword;

    @Value("${mqtt.username}")
    public void setAuthUsername(String authUsername) {
        BaseAuthHttpUtils.authUsername = authUsername;
    }

    @Value("${mqtt.password}")
    public void setAuthPassword(String authPassword) {
        BaseAuthHttpUtils.authPassword = authPassword;
    }

    /**
     * get请求
     * @param strUrl
     * @return
     */
    public static String httpURLConnectionGet(String strUrl){
        BufferedReader in = null;
        String username = authUsername;
        String password = authPassword;
        String auth = username+":"+password;
        //对其进行加密
        byte[] rel = Base64.encodeBase64(auth.getBytes());
        String res = new String(rel);
        try {
            //获取访问地址URL,注意GET请求若URL中包含中文字符的话,在高版本TOMCAT中会认为是不合法字符,可改为POST方式
            URL url = new URL(strUrl);
            //创建HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //添加请求头
//            conn.setRequestProperty("USER-TOKEN","eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyc2oiLCJ1c2VySWQiOiJyZWRpczp1c2VyOnRva2VuOjI3IiwiaWF0IjoxNjAzMzUwODcyLCJleHAiOjE2MDM5NTU2NzJ9.3KOsFrzpJbz_p5vjVzL3sGTWFm1yAKAAaDpKeg4DJDw");
            //请求方式,默认是GET
            conn.setRequestMethod("GET");
            //连接主机的超时时间（单位：毫秒）
            conn.setConnectTimeout(30000);
            //设置认证
            conn.setRequestProperty("Authorization","Basic " + res);
            //从主机读取数据的超时时间（单位：毫秒）
            conn.setReadTimeout(30000);
            //设置是否输出,默认是false
            conn.setDoOutput(false);
            //设置是否读入,默认是true
            conn.setDoInput(true);
            String result = "";
            int code = conn.getResponseCode();
            if(code == 200){
                //定义BufferedReader输入流读取响应,getInputStream()会自动建立连接,无需手动调用connect()连接
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                //关闭输入流
                in.close();
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Post请求
     * @param strUrl
     * @return
     */
    public static String httpURLConnectionPost(String strUrl, Map params){
        String jsonString = JSONObject.toJSONString(params);
        PrintWriter out = null;
        BufferedReader in = null;

        String username = authUsername;
        String password = authPassword;
        String auth = username+":"+password;
        //对其进行加密
        byte[] rel = Base64.encodeBase64(auth.getBytes());
        String res = new String(rel);
        try {
            //获取访问地址URL
            URL url = new URL(strUrl);
            //创建HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求格式
            conn.setRequestProperty("Content-type", "application/json");
            //设置编码语言
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            //请求方式,默认是GET
            conn.setRequestMethod("POST");
            //连接主机的超时时间（单位：毫秒）
            conn.setConnectTimeout(30000);
            //从主机读取数据的超时时间（单位：毫秒）
            conn.setReadTimeout(30000);
            //设置认证
            conn.setRequestProperty("Authorization","Basic " + res);
            //设置是否输出,post请求参数要放在 http正文内,需设为true,默认是false
            conn.setDoOutput(true);
            //设置是否读入,默认是true
            conn.setDoInput(true);
            //获取字符输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
            //发送请求参数
            out.print(jsonString);
            //刷新输出流
            out.flush();
            //关闭输出流
            out.close();
            String result = "";
            int code = conn.getResponseCode();
            if(code == 200){
                //定义BufferedReader输入流读取响应,getInputStream()会自动建立连接,无需手动调用connect()连接
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                //关闭输入流
                in.close();
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
